package operator.combine;

import io.reactivex.Observable;
import io.reactivex.functions.BiFunction;
import io.reactivex.functions.Consumer;
import util.Printer;

class ReduceOperator {

    public static void main(String[] args) {
//        reduce1();
        reduce2();
    }


    /**
     * Reduce操作符应用一个函数接收Observable发射的数据和函数的计算结果作为下次计算的参数，输出最后的结果。
     * 跟前面我们了解过的scan操作符很类似，只是scan会输出每次计算的结果，而reduce只会输出最后的结果
     *
     */
    static void reduce1(){
        Observable.range(1, 20)
                .reduce(new BiFunction<Integer, Integer, Integer>() {
                    @Override
                    public Integer apply(Integer integer, Integer integer2) throws Exception {
                        return integer + integer2;
                    }
                })
                .subscribe(new Consumer<Integer>() {
                    @Override
                    public void accept(Integer integer) throws Exception {
                        Printer.print(integer);
                    }
                });
    }

    static void reduce2(){
        Observable.just("1", "2", "3")
                .reduce(new BiFunction<String, String, String>() {
                    @Override
                    public String apply(String s1, String s2) throws Exception {
                        return s1 + " " +s2;
                    }
                })
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String result) throws Exception {
                        Printer.print(result);
                    }
                });

        Observable.just("4", "5", "6")
                .reduce("start", new BiFunction<String, String, String>() {
                    @Override
                    public String apply(String s, String s2) throws Exception {
                        return s + " " + s2;
                    }
                })
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String result) throws Exception {
                        Printer.print(result);
                    }
                });
    }

}
